import Vue from 'vue'
import VueRouter from 'vue-router'


Vue.use(VueRouter);

function hasUrl(to,next) {
  //1.先获取本地存储里面存储的用户权限有哪些
  let menus_url = JSON.parse(localStorage.getItem("userinfo") || "{}").menus_url;
  //2.判断你当前要访问的路由在不在你的权限中
  // console.log(menus_url); //权限数组
  // console.log(to.path);   // /index/menu
  // menus_url.include(to.path)  //判断数组中是否有这个元素的存在，true，false
  if (menus_url.includes(to.path)) {
    next();
  } else {
    next("/login")
  }
}

export let pathArr = [{
  path: "menu",
  component: () => import("../views/menu/menu.vue"),
  meta: { title: "菜单管理" },
  //路由独享守卫
  beforeEnter(to, from, next) {hasUrl(to,next)}
},
{
  path: "role",
  component: () => import("../views/role/role.vue"),
  meta: { title: "角色管理" },
    //路由独享守卫
    beforeEnter(to, from, next) {hasUrl(to,next)}
},
{
  path: "user",
  component: () => import("../views/user/user.vue"),
  meta: { title: "管理员管理" },
    //路由独享守卫
    beforeEnter(to, from, next) {hasUrl(to,next)}
},
{
  path: "cate",
  component: () => import("../views/cate/cate.vue"),
  meta: { title: "商品分类" },
    //路由独享守卫
    beforeEnter(to, from, next) {hasUrl(to,next)}
},
{
  path: "specs",
  component: () => import("../views/specs/specs.vue"),
  meta: { title: "商品规格" },
    //路由独享守卫
    beforeEnter(to, from, next) {hasUrl(to,next)}
},
{
  path: "goods",
  component: () => import("../views/goods/goods.vue"),
  meta: { title: "商品管理" },
    //路由独享守卫
    beforeEnter(to, from, next) {hasUrl(to,next)}
},
{
  path: "member",
  component: () => import("../views/member/member.vue"),
  meta: { title: "会员管理" },
    //路由独享守卫
    beforeEnter(to, from, next) {hasUrl(to,next)}
},
{
  path: "banner",
  component: () => import("../views/banner/banner.vue"),
  meta: { title: "轮播图管理" },
    //路由独享守卫
    beforeEnter(to, from, next) {hasUrl(to,next)}
},
{
  path: "seck",
  component: () => import("../views/seck/seck.vue"),
  meta: { title: "秒杀活动" },
    //路由独享守卫
    beforeEnter(to, from, next) {hasUrl(to,next)}
}]

const routes = [
  {
    path: "/login",
    component: () => import("../pages/login.vue"),
    meta: {
      title: "登录"
    }
  },
  {
    path: "/index",
    component: () => import("../pages/index.vue"),
    meta: {
      title: "首页"
    },
    children: [
      {
        path: "home",
        component: () => import("../views/home.vue"),
        meta: { title: "首页" }
      },
      // 展开
      ...pathArr,
      {
        path: "",
        redirect: "home"
      }
    ]
  },
  {
    path: "*",
    redirect: "/login"
  }
]

const router = new VueRouter({
  routes
})

//-----全局路由导航守卫---------------
router.beforeEach((to, from, next) => {
  //to.path : 去哪的地址
  //next:往下

  //1.如果你去的是登录
  if (to.path == "/login") {
    next();
    return;
  }

  //2.登录了就能进，如果本地存储了数据
  if (localStorage.getItem("userinfo")) {
    next();
    return;
  }

  //3.其他情况，去登录
  // next 不行就用push router.push()
  next("/login")
});

export default router
